package com.shenmazong.demowebsocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket")
public class MyWebSocket {

    // 全部在线会话 PS: 基于场景考虑 这里使用线程安全的Map存储会话对象。
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();
    private Session _session;


    @OnOpen
    public void onOpen(Session session) {
        this._session = session;
        onlineSessions.put(session.getId(), session);

        try {
            sendMessageAll("欢迎光临寒舍！！！");
        }catch (Exception e) {
            log.error("onOpen", e);
        }

        log.info("有新连接加入，当前在线数为" + onlineSessions.size());
    }

    @OnClose
    public void onClose(Session session) {

        onlineSessions.remove(session.getId());
        log.info("有一连接关闭！当前在线数为" + onlineSessions.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        sendMessageAll(session.getId() + ":" + message);
        log.info("来自客户端 " + " 的消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("LoginResultWebSocket 发生错误");
        error.printStackTrace();
    }

    public void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    public void sendMessageAll(String message) {
        for(String key : onlineSessions.keySet()){
            Session session = onlineSessions.get(key);

            try {
                sendMessage(session, message);
            }
            catch (Exception e) {
                log.error("sendMessageAll", e);
            }
        }
    }
}
